package com.tbynet.wordpress.admin.user;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.tbynet.wordpress.admin.AdminController;
import com.tbynet.wordpress.framework.bean.Permission;
import com.tbynet.wordpress.framework.bean.Role;
import com.tbynet.wordpress.framework.kit.PassKit;
import com.tbynet.wordpress.model.Usermeta;
import com.tbynet.wordpress.model.Users;
import com.tbynet.wordpress.service.UserService;

public class UserAdminController extends AdminController {

	@Inject
	UserService userService;
	
	public void index() {
		keepPara("q");
		render("index.html");
	}
	
	public void search() {
		String q = getPara("q");
		
		Page<Users> page = userService.search(getPage(), getSize(), q);
		for(Users user : page.getList()) {
			Usermeta role = userService.getUsermeta(user.getID(), "role");
			if(null != role) {
				user.put("role", role.getMetaValue());
			}
		}
		
		ok(Ret.by("data", page));
	}
	
	public void create() {
		render("create.html");
	}
	
	public void edit() throws Exception {
		Object ID = get("user_id");
		if(null == ID) {
			set("error", "用户ID无效.");
			render("../error.html");
			return;
		}
		
		Users user = userService.getUser(ID);
		List<Usermeta> metas = userService.getUsermetas(user.getID());
		for(Usermeta meta : metas) {
			if(meta.getMetaKey().equals(Usermeta.session_tokens)) {
				set(meta.getMetaKey(), meta.getSessionTokens());
			} else if(meta.getMetaKey().equals(Usermeta.permissions)) {
				user.put(meta.getMetaKey(), meta.getPermissions().toLinkedHashMap());
			} else if(meta.getMetaKey().equals(Usermeta.wp_capabilities)) {
				set(meta.getMetaKey(), meta.getWpCapabilities().toLinkedHashMap());
			} else {
				user.put(meta.getMetaKey(), meta.getMetaValue());
			}
		}
		
		set("user", user);
		
		render("edit.html");
	}
	
	public void save() throws Exception {
		String userLogin = getPara("user_login");
		String email = getPara("email");

		String firstName = getPara("first_name");
		String lastName = getPara("last_name");
		
		String url = getPara("url");
		String userPass = getPara("user_pass");
		
		boolean sendUserNotification = getParaToBoolean("send_user_notification", false);
		String role = getPara("role");
		
		String nickname = userLogin;
		String description = "";
		String richEditing = "true";
		String syntaxHighlighting = "true";
		String commentShortcuts = "false";
		String adminColor = "fresh";
		String useSSL = "0";
		String showAdminBarFront = "true";
		String locale = "";
		String wpUserLevel = "0";
		String dismissedWpPointers = "wp496_privacy";
		
		if(StrKit.isBlank(userLogin)) {
			fail("用户名不能为空");
			return;
		}
		if(StrKit.isBlank(email)) {
			fail("电子邮件不能为空");
			return;
		}
		if(StrKit.isBlank(userPass)) {
			fail("密码不能为空");
			return;
		}
		
		Users user = new Users();
		user.setUserLogin(userLogin);
		user.setUserPass(PassKit.encrypt(userPass));
		user.setUserEmail(email);
		user.setUserUrl(url);
		user.setUserNicename(userLogin);
		user.setDisplayName(userLogin);
		user.setUserRegistered(new Date(System.currentTimeMillis()));
		
		user.setNickname(nickname);
		user.setFirstName(firstName);
		user.setLastName(lastName);
		user.setDescription(description);
		user.setRichEditing(richEditing);
		user.setSyntaxHighlighting(syntaxHighlighting);
		user.setCommentShortcuts(commentShortcuts);
		user.setAdminColor(adminColor);
		user.setUseSSL(useSSL);
		user.setShowAdminBarFront(showAdminBarFront);
		user.setLocale(locale);
		if(StrKit.notBlank(role)) {
			user.setRole(role);
			List<Kv> permissions = new ArrayList<Kv>();
			for(Permission permission : Role.getPermissions(role)) {
				permissions.add(Kv.by(permission.getName(), Kv.by("action", permission.getAction()).set("scope", permission.getScope())));
			}
			user.setPermissions(permissions.toArray());
		}
		user.setWpUserLevel(wpUserLevel);
		user.setDismissedWpPointers(dismissedWpPointers);
		
		if(sendUserNotification) {
			// to do send email
		}
		
		if(userService.save(user)) {
			ok(Ret.by("msg", "添加用户成功").set("data", user.getID()));
		} else {
			fail("添加用户失败，请联系管理员");
		}
	}
	
	public void update() throws Exception {
		String userId = get("user_id");
		String displayName = getPara("display_name");
		String email = getPara("email");
		String url = getPara("url");
		String userPass = getPara("user_pass");

		String firstName = getPara("first_name");
		String lastName = getPara("last_name");
		String nickname =getPara("nickname");
		String locale = getPara("locale");
		String description = getPara("description");
		String adminColor = getPara("admin_color");
		String richEditing = getPara("rich_editing");
		String commentShortcuts = getPara("comment_shortcuts");
		String adminBarFront = getPara("admin_bar_front");
		String role = getPara("role");
		String[] permissions = getParaValues("permission");
		
		Users user = userService.getUser(userId);
		//更新用户信息
		user.setDisplayName(displayName);
		user.setUserEmail(email);
		user.setUserUrl(url);
		if(StrKit.notBlank(userPass)) {
			userPass = PassKit.encrypt(userPass);
			user.setUserPass(userPass);
		}
		
		//更新用户元数据
		List<Usermeta> metas = new ArrayList<Usermeta>();
		
		if(StrKit.notBlank(firstName)) {
			Usermeta meta = userService.getUsermeta(user.getID(), Usermeta.first_name);
			if(null == meta) {
				meta = new Usermeta();
				meta.setUserId(user.getID());
			}
			meta.setFirstName(firstName);
			metas.add(meta);
		}
		if(StrKit.notBlank(lastName)) {
			Usermeta meta = userService.getUsermeta(user.getID(), Usermeta.last_name);
			if(null == meta) {
				meta = new Usermeta();
				meta.setUserId(user.getID());
			}
			meta.setLastName(lastName);
			metas.add(meta);
		}
		if(StrKit.notBlank(nickname)) {
			Usermeta meta = userService.getUsermeta(user.getID(), Usermeta.nickname);
			if(null == meta) {
				meta = new Usermeta();
				meta.setUserId(user.getID());
			}
			meta.setNickname(nickname);
			metas.add(meta);
		}
		if(StrKit.notBlank(locale)) {
			Usermeta meta = userService.getUsermeta(user.getID(), Usermeta.locale);
			if(null == meta) {
				meta = new Usermeta();
				meta.setUserId(user.getID());
			}
			meta.setLocale(locale);
			metas.add(meta);
		}
		if(StrKit.notBlank(description)) {
			Usermeta meta = userService.getUsermeta(user.getID(), Usermeta.description);
			if(null == meta) {
				meta = new Usermeta();
				meta.setUserId(user.getID());
			}
			meta.setDescription(description);
			metas.add(meta);
		}
		if(StrKit.notBlank(adminColor)) {
			Usermeta meta = userService.getUsermeta(user.getID(), Usermeta.admin_color);
			if(null == meta) {
				meta = new Usermeta();
				meta.setUserId(user.getID());
			}
			meta.setAdminColor(adminColor);
			metas.add(meta);
		}
		if(StrKit.notBlank(richEditing)) {
			Usermeta meta = userService.getUsermeta(user.getID(), Usermeta.rich_editing);
			if(null == meta) {
				meta = new Usermeta();
				meta.setUserId(user.getID());
			}
			meta.setRichEditing(richEditing);
			metas.add(meta);
		}
		if(StrKit.notBlank(role)) {
			Usermeta meta = userService.getUsermeta(user.getID(), Usermeta.role);
			if(null == meta) {
				meta = new Usermeta();
				meta.setUserId(user.getID());
			}
			meta.setRole(role);
			metas.add(meta);
		}
		if(null != permissions) {
			Usermeta meta = userService.getUsermeta(user.getID(), Usermeta.permissions);
			if(null == meta) {
				meta = new Usermeta();
				meta.setUserId(user.getID());
			}
			List<Kv> list = new ArrayList<Kv>();
			for(String name : permissions) {
				Permission permission = Permission.getPermission(name);
				list.add(Kv.by(permission.getName(), Kv.by("action", permission.getAction()).set("scope", permission.getScope())));
			}
			meta.setPermissions(list.toArray());
			metas.add(meta);
		}
		if(StrKit.notBlank(commentShortcuts)) {
			Usermeta meta = userService.getUsermeta(user.getID(), Usermeta.comment_shortcuts);
			if(null == meta) {
				meta = new Usermeta();
				meta.setUserId(user.getID());
			}
			meta.setCommentShortcuts(commentShortcuts);
			metas.add(meta);
		}
		if(StrKit.notBlank(adminBarFront)) {
			Usermeta meta = userService.getUsermeta(user.getID(), Usermeta.show_admin_bar_front);
			if(null == meta) {
				meta = new Usermeta();
				meta.setUserId(user.getID());
			}
			meta.setShowAdminBarFront(adminBarFront);
			metas.add(meta);
		}
		
		if(userService.update(user, metas)) {
			ok(Ret.by("msg", "更新用户成功").set("data", user.getID()));
		} else {
			fail("更新用户失败，请联系管理员");
		}
	}
	
	public void permission() {
		String role = getPara("role");
		
		List<String> permissions = new ArrayList<String>();
		for(Permission permission : Role.getPermissions(role)) {
			permissions.add(permission.getName());
		}
		
		ok(Ret.by("data", permissions));
	}
}
